<?php
namespace ImiDemo\HttpDemo\MainServer\Controller;

use Imi\Db\Db;
use Imi\Util\MuiltDefer;
use Imi\Controller\HttpController;
use Imi\Db\Annotation\Transaction;
use Imi\Server\View\Annotation\View;
use Imi\Server\Route\Annotation\Route;
use Imi\Server\Route\Annotation\Action;
use Imi\Server\Route\Annotation\Controller;

/**
 * 数据库操作 演示
 * @Controller("/Db/")
 * @View(renderType="json")
 */
class DbController extends HttpController
{
    /**
     * 数据库操作 演示
     * 访问：http://127.0.0.1:8080/Db/test
     * 
     * @Action
     * 
     * 自动开启事务：
     * @Transaction
     * 
     * @return void
     */
    public function test()
    {
        $list = Db::query()->from('tb_test')
                           ->where('b', '=', 'bbb')
                           ->select()
                           ->getArray();
        return [
            'list'    =>    $list,
        ];
    }

    /**
     * 延迟收包 演示
     * 模拟调用两个耗时1秒的SQL，最终总共耗时仅需1秒
     * 访问：http://127.0.0.1:8080/Db/defer
     * 
     * @Action
     * 
     * @return void
     */
    public function defer()
    {
        $time = microtime(true);

        $db1 = Db::query(null, null, true)->setDefer();
        $db2 = Db::query(null, null, true)->setDefer();

        $defer1 = $db1->execute('select sleep(1)');
        $defer2 = $db2->execute('select sleep(1)');

        return [
            'result1'    =>    $defer1->getScalar(),
            'result2'    =>    $defer2->getScalar(),
            'time'    =>    microtime(true) - $time,
        ];
        return [];
    }

}